import { useState, useImperativeHandle, forwardRef } from 'react';
import styles from './index.less';
import { Modal, Table, Button, DatePicker } from 'antd';
import moment from 'moment';
import AutoSizer from 'react-virtualized/dist/commonjs/AutoSizer';
import { connect } from 'umi';
import { tableLocale } from '@/tool/components/PageEmpty';
import { TRMessage } from '#/components';
import { HttpCode } from '#/utils/contacts';
import { operateLogModal, updateIcon } from '@/assets';
import { CheckCircleOutlined, CloseCircleOutlined } from '#/utils/antdIcons.js';
import {
  fetchStatusPageViewData_SD,
  undoCommit,
} from '@/pages/Tianji/TenDaysCentralizedBidding/services';
import { getDataSource } from '@/pages/Tianji/TenDaysCentralizedBidding/helper';

const { Column, ColumnGroup } = Table;

function SearchStatusModal({ formData }, ref) {
  useImperativeHandle(ref, () => ({
    initHandle,
  }));

  const [showModal, setShowModal] = useState(false),
    [searchStatusData, setSearchStatusData] = useState({}),
    [date, setDate] = useState(null),
    [loading, setLoading] = useState(false);

  const initHandle = () => {
    setShowModal(true);
    fetchStatusInfo(formData?.date);
  };

  const fetchStatusInfo = async (date) => {
    setLoading(true);
    const res = await fetchStatusPageViewData_SD(moment(date).format('YYYYMMDD'));
    setLoading(false);
    if (res?.statusCode === HttpCode.SUCCESS) {
      setSearchStatusData(getDataSource(res.data));
    } else {
      TRMessage.error(res?.message || '获取状态查询信息失败');
    }
  };

  const onundoCommit = async (id) => {
    const res = await undoCommit(id);
    if (res?.statusCode === HttpCode.SUCCESS) {
      TRMessage.success(res?.message || '撤销成功');
      fetchStatusInfo(date);
    } else {
      TRMessage.error(res?.message || '撤销失败');
    }
  };

  return (
    <Modal
      className={styles.submitStatusModal}
      centered={true}
      title={
        <div className={styles.modalTitle}>
          <img src={operateLogModal} />
          <span className={styles.text}>状态查询</span>
        </div>
      }
      visible={showModal}
      footer={null}
      onCancel={() => {
        setShowModal(false);
      }}
    >
      <div className={styles.unitBox}>
        <div className={styles.unit}>
          <span className={styles.label}>单位(量：</span>MWh
          <span className={styles.label}>价：</span>元/MWh<span className={styles.label}>)</span>
        </div>
        <div className={styles.date}>
          申报日
          <DatePicker
            className={`border-radius-5 ${styles.dataPicker}`}
            allowClear={false}
            onChange={(e) => {
              fetchStatusInfo(e);
              setDate(e);
            }}
            defaultValue={moment(formData?.date)}
            format="YYYYMMDD"
          />
        </div>
      </div>
      <div style={{ flex: 1, overflow: 'hidden' }}>
        <AutoSizer>
          {({ height, width }) => {
            return (
              <div style={{ width, height, display: 'flex' }}>
                <Table
                  loading={loading}
                  className={styles.table}
                  dataSource={searchStatusData.dataSource}
                  rowKey="date"
                  locale={tableLocale}
                  bordered={true}
                  pagination={false}
                  scroll={{ x: true, y: height - 58 }}
                >
                  <Column
                    title="日期"
                    align="center"
                    dataIndex="date"
                    key="date"
                    width={76}
                    fixed="left"
                  />
                  {searchStatusData?.columnData?.map((item) => (
                    <ColumnGroup title={item.unitTitle} key={item.unitId}>
                      <Column
                        title="交易方向"
                        dataIndex={item.unitId + '_tradeType'}
                        key={item.unitId + '_tradeType'}
                        align="center"
                        className={styles.columnItem}
                        render={(text) => {
                          switch (text) {
                            case 'buy':
                              return <span className={styles.green}>买入</span>;
                            case 'sale':
                              return <span className={styles.red}>卖出</span>;
                            default:
                              return <span>-</span>;
                          }
                        }}
                      />
                      <Column
                        title="申报电量"
                        dataIndex={item.unitId + '_power'}
                        key={item.unitId + '_power'}
                        align="center"
                        className={styles.columnItem}
                      />
                      <Column
                        title="申报电价"
                        dataIndex={item.unitId + '_price'}
                        key={item.unitId + '_price'}
                        align="center"
                        className={styles.columnItem}
                      />
                      <Column
                        title="申报状态"
                        dataIndex={item.unitId + '_declareState'}
                        key={item.unitId + '_declareState'}
                        align="center"
                        className={styles.columnItem}
                        render={(text) => {
                          switch (text) {
                            case 'fail':
                              return (
                                <>
                                  <CloseCircleOutlined
                                    className={styles.red}
                                    style={{ marginRight: '4px' }}
                                  />
                                  失败
                                </>
                              );
                            case 'success':
                              return (
                                <>
                                  <CheckCircleOutlined
                                    className={styles.green}
                                    style={{ marginRight: '4px' }}
                                  />
                                  成功
                                </>
                              );
                            default:
                              return <span>-</span>;
                          }
                        }}
                      />
                      <Column
                        title="操作"
                        align="center"
                        width={56}
                        render={(text, record) => {
                          return (
                            <Button
                              type="link"
                              style={{ fontSize: '12px', padding: 0, width: 24 }}
                              disabled={record[item.unitId + '_undoState']}
                              onClick={() => {
                                onundoCommit(record[item.unitId + '_id']);
                              }}
                            >
                              撤销
                            </Button>
                          );
                        }}
                      />
                    </ColumnGroup>
                  ))}
                </Table>
              </div>
            );
          }}
        </AutoSizer>
      </div>
    </Modal>
  );
}

export default connect(
  ({ global, tenDaysCentralizedBidding }) => ({
    formData: tenDaysCentralizedBidding.formData,
  }),
  null,
  null,
  { forwardRef: true },
)(forwardRef(SearchStatusModal));
